"use strict";
const path = require('path');
const Koa = require('koa');
const router = require('koa-router')();
const staticServer=require('koa-static');
const webpack = require("webpack");
const webpackDev = require("webpack-dev-middleware");
const webpackHot = require('webpack-hot-middleware');
const PassThrough = require('stream').PassThrough;
const HtmlwebpackPlugin = require('html-webpack-plugin');

// 获取配置参数
const npmArgv = process.argv.splice(2);

// 获取系统名称
const systemName = npmArgv[0];

// 获取系统名称
const versionName = npmArgv[1];

// 获取端口号
const portName = npmArgv[2] ? npmArgv[2] : '3000';

// 断言
console.assert(systemName, '缺少系统名称');

// 断言
console.assert(versionName, '缺少版本号');

// 打印输出运行
console.log(`开始启动环境 => (系统: ${systemName}, 版本号: ${versionName}, 端口号: ${portName})`);

// 实例化方法
const app = new Koa();

// webpack配置
const compiler = webpack({
    mode: 'production',
    entry: path.join(__dirname, "./polyfills.js"),
    plugins: [
        new HtmlwebpackPlugin({
            title: 'test',
            template: '!!pug-loader!./webpack/index.pug',
            inject: false,
            environment: process.env.NODE_ENV,
            minify: {
                minimize: false,
                caseSensitive: true,
                collapseWhitespace: true,
                removeComments: true,
                removeEmptyAttributes: true,
                removeOptionalTags: true,
                removeRedundantAttributes: true,
                useShortDoctype: true
            }
        })
    ],
    module: {
        rules: [
            {
                test: /\.pug$/,
                exclude: ['/node_modules/'],
                loader: 'pug-loader',
                query: {
                    a: {
                        b: 'yo'
                    }
                }
            }
        ]
    }
});

// 中间件
const middleware = app => {

    // 普通开发中间件
    const devMiddleware = (compiler, opts) => {
        const middleware = webpackDev(compiler, opts);
        return async (ctx, next) => {
            await middleware(ctx.req, {
                end: (content) => {
                    ctx.body = content
                },
                setHeader: (name, value) => {
                    ctx.set(name, value)
                }
            }, next);
        }
    };

    // 热重载中间件
    const hotMiddleware = (compiler, opts) => {
        const middleware = webpackHot(compiler, opts);
        return async (ctx, next) => {
            let stream = new PassThrough();
            // 数据流
            ctx.body = stream;
            await middleware(ctx.req, {
                write: stream.write.bind(stream),
                writeHead: (status, headers) => {
                    ctx.status = status;
                    ctx.set(headers);
                }
            }, next);
        }  
    };

    app.use(staticServer(path.join(__dirname,'./')));
    app.use(router.routes());
    // webpack中间件
    app.use(devMiddleware(compiler));
    app.use(hotMiddleware(compiler));
    return app;
};

middleware(app).listen(portName, () => {
    console.log(`${portName}服务器已启动`);
});
